package com.example.hotel_lxy.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.example.hotel_lxy.R;
import com.example.hotel_lxy.application.ARouterPath;
import com.example.hotel_lxy.bean.BeanBean;
import com.example.hotel_lxy.bean.ZeroSpSourceBean;
import com.example.hotel_lxy.bean.ZeroSpViewBean;
import com.example.hotel_lxy.net.Api;
import com.example.hotel_lxy.ui.dialog.DataSelectionDialog;
import com.example.hotel_lxy.ui.dialog.DataSelectionDialogs;
import com.example.hotel_lxy.ui.dialog.StoreDateDialog;
import com.example.hotel_lxy.utils.DatePhotoUtils;
import com.example.hotel_lxy.utils.DateUtils;
import com.example.hotel_lxy.utils.JurisdictionUtils;
import com.example.hotel_lxy.utils.SPUtils;
import com.ysxsoft.common_base.base.BaseActivity;
import com.ysxsoft.common_base.base.RBaseAdapter;
import com.ysxsoft.common_base.base.RViewHolder;
import com.ysxsoft.common_base.utils.JsonUtils;
import com.ysxsoft.common_base.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 零点预定页
 */
@Route(path = "/main/ZeroPointReserveActivity")
public class ZeroPointReserveActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.text_date)
    TextView textDate;
    @BindView(R.id.text_txl)
    TextView textTxl;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_photo)
    EditText editPhoto;
    @BindView(R.id.line_time)
    LinearLayout lineTime;
    @Autowired
    String id;
    @Autowired
    String name;
    @Autowired
    String time_type;
    @Autowired
    String time;
    @BindView(R.id.text_title_name)
    TextView textTitleName;
    @BindView(R.id.text_time)
    TextView textTime;
    @BindView(R.id.tv_view)
    TextView tvView;
    @BindView(R.id.tv_source)
    TextView tvSource;
    @BindView(R.id.text_add)
    TextView textAdd;
    @BindView(R.id.text_add_mess)
    TextView textAddMess;
    @BindView(R.id.rb_nan)
    RadioButton rbNan;
    @BindView(R.id.rb_nv)
    RadioButton rbNv;
    @BindView(R.id.rg_sex)
    RadioGroup rgSex;
    @BindView(R.id.text_number)
    EditText textNumber;
    @BindView(R.id.edit_qt)
    EditText editQt;
    private String director_id;
    private String source_id;

    List<ZeroSpSourceBean.DataBean.ListBean> list;

    @Autowired
    String Way;
    public static void start(String id, String name, String time,String Way, String time_type) {
        ARouter.getInstance().build(ARouterPath.getZeroPointReserveActivity())
                .withString("id", id)
                .withString("name", name)
                .withString("time", time)
                .withString("Way", Way)
                .withString("time_type", time_type)
                .navigation();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_zero_point_reserve;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void doWork() {
        super.doWork();
        ARouter.getInstance().inject(this);
        Log.e("TAG",time+"  雅间id");
        textTitleName.setText("【雅间名称】" + name);
        if (time_type.equals("1")) {
            textTime.setText("【到店日期】 " + time+Way + "  中午");
        } else {
            textTime.setText("【到店日期】 " + time +Way+ "  晚上");
        }

        back.setOnClickListener(this);
        textTxl.setOnClickListener(this);
        lineTime.setOnClickListener(this);
        tvView.setOnClickListener(this);
        tvSource.setOnClickListener(this);
        textAdd.setOnClickListener(this);
        textAddMess.setOnClickListener(this);
        textDate.setOnClickListener(this);

        rgSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (group.getCheckedRadioButtonId()) {
                    case R.id.rb_nan:
                        rbNv.setChecked(false);
                        break;
                    case R.id.rb_nv:
                        rbNan.setChecked(false);
                        break;
                }
            }
        });
        showData();
    }

    private void showData() {
        OkHttpUtils.post()
                .url(Api.POST_ZERO_VIEW)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户经理onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户经理onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ZeroSpSourceBean zeroSpSourceBean = JsonUtils.parseByGson(response, ZeroSpSourceBean.class);
                        if (beanBean.getCode().equals("0")) {
                            list = zeroSpSourceBean.getData().getList();
                            if(list.size()!=0){
                                for (int i = 0; i <list.size() ; i++) {
                                    boolean getuserid = JurisdictionUtils.getuserid(mContext, list.get(i).getId() + "");
                                    if(getuserid){
                                        director_id =list.get(i).getId() + "";
                                        tvView.setText("" +list.get(i).getUsername());
                                        return;
                                    }

                                }

                            }
                        }
                    }
                });
        OkHttpUtils.post()
                .url(Api.POST_ZERO_SOURCE)
                .addHeader("flag", SPUtils.get(mContext, "token", "").toString())
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "客户来源onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "客户来源onResponse   " + response);
                        BeanBean beanBean= JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        ZeroSpSourceBean zeroSpSourceBean = JsonUtils.parseByGson(response, ZeroSpSourceBean.class);
                        if (beanBean.getCode().equals("0")) {
                            list = zeroSpSourceBean.getData().getList();
                            if(list.size()!=0){
                                source_id =list.get(0).getId() + "";
                                tvSource.setText("" +list.get(0).getName());
                            }
                        }
                    }
                });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.text_txl:
//                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
//                startActivityForResult(intent, 0);
                judgePermission();
                break;
            case R.id.line_time:
                showDataTime();
                break;
            case R.id.text_date:
                showDataTime();
                break;
            case R.id.tv_view://客户经理
                boolean xzyudingren = JurisdictionUtils.getXzyudingren(ZeroPointReserveActivity.this);
                if(!xzyudingren){
                    ToastUtils.longToast(ZeroPointReserveActivity.this,"当前账号没有操作权限哦");
                    return;
                }
                DataSelectionDialogs.show(ZeroPointReserveActivity.this,null,Api.POST_ZERO_VIEW).setListener(new DataSelectionDialogs.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String id, String name) {
                        director_id =id + "";
                        tvView.setText("" +name);
                    }
                });
                break;
            case R.id.tv_source://客户来源
                DataSelectionDialogs.show(ZeroPointReserveActivity.this,null,Api.POST_ZERO_SOURCE).setListener(new DataSelectionDialogs.OnDialogClickListener() {
                    @Override
                    public void onPositiveClick(String id, String name) {
                        source_id = id + "";
                        tvSource.setText("" + name);
                    }
                });
                break;
            case R.id.text_add:
                if (editPhoto.getText().toString().length() != 11) {
                    ToastUtils.show(ZeroPointReserveActivity.this, "请输入正确的手机号码");
                    return;
                }
                showAddZero(1);
                break;
            case R.id.text_add_mess:
                if (editPhoto.getText().toString().length() != 11) {
                    ToastUtils.show(ZeroPointReserveActivity.this, "请输入正确的手机号码");
                    return;
                }
                showAddZero(2);
                break;
        }
    }

    private void showDataTime() {
        if(time_type.equals("2")){
            StoreDateDialog.show(ZeroPointReserveActivity.this, null, "2",time)
                    .setListener(new StoreDateDialog.OnDialogClickListener() {
                        @Override
                        public void onPositiveClick(String s) {
                            textDate.setText("" + s);
                        }
                    });
        }else{
            StoreDateDialog.show(ZeroPointReserveActivity.this, null, "1",time)
                    .setListener(new StoreDateDialog.OnDialogClickListener() {
                        @Override
                        public void onPositiveClick(String s) {
                            textDate.setText("" + s);
                        }
                    });
        }
    }

    private void showAddZero(int type) {

        if(editName.getText().toString().equals("")){
            ToastUtils.show(ZeroPointReserveActivity.this,"客户姓名不能为空");
            return;
        }
        if(textDate.getText().toString().equals("")){
            ToastUtils.show(ZeroPointReserveActivity.this,"到店时间不能为空");
            return;
        }
        int sex_type = 1;
        if (rbNan.isChecked()) {
            sex_type = 1;
        } else {
            sex_type = 2;
        }

//        Log.e("TAG","flag   "+  SPUtils.get(ZeroPointReserveActivity.this, "token", "").toString());
//        Log.e("TAG","eid   "+  id);
//        Log.e("TAG","end_time   "+  time);
//        Log.e("TAG","noon   "+  time_type);
//        Log.e("TAG","people   "+  textNumber.getText().toString());
//        Log.e("TAG","name   "+  editName.getText().toString());
//        Log.e("TAG","sex   "+  sex_type);
//        Log.e("TAG","mobile   "+  editPhoto.getText().toString());
//        Log.e("TAG","time   "+  textDate.getText().toString());
//        Log.e("TAG","director_id   "+  director_id);
//        Log.e("TAG","content   "+  editQt.getText().toString());
//        Log.e("TAG","source_id   "+  source_id);
//        Log.e("TAG","type   "+  type);
        OkHttpUtils.post()
                .url(Api.POST_ZERO_RESERVATION)
                .addHeader("flag", SPUtils.get(ZeroPointReserveActivity.this, "token", "").toString())
                .addParams("eid", id)
                .addParams("end_time", time)
                .addParams("noon", time_type)
                .addParams("people", textNumber.getText().toString())
                .addParams("name", editName.getText().toString())
                .addParams("sex", sex_type + "")
                .addParams("mobile", editPhoto.getText().toString())
                .addParams("time", textDate.getText().toString())
                .addParams("director_id", director_id)
                .addParams("content", editQt.getText().toString())
                .addParams("source_id",source_id)
                .addParams("type",type+"")
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("TAG", "零点预定onError   " + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("TAG", "零点预定onResponse   " + response);
                        BeanBean beanBean = JsonUtils.parseByGson(response, BeanBean.class);
                        if(beanBean.getCode().equals("0")){
                            ToastUtils.show(ZeroPointReserveActivity.this,beanBean.getMsg());
                            finish();
                        }else   if(beanBean.getCode().equals("4")){
                            SPUtils.put(mContext,"token","");
                            Intent intent = new Intent(mContext, LoginActivity.class).
                                    setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            return;
                        }
                        else{
                            ToastUtils.show(ZeroPointReserveActivity.this,beanBean.getMsg());
                        }

                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (data == null) {
                    return;
                }
                Uri uri = data.getData();
                String[] contacts = DatePhotoUtils.getPhoneContacts(ZeroPointReserveActivity.this, uri);
                editName.setText("" + contacts[0]); //contacts[1]
                editPhoto.setText("" + contacts[1].trim().replace(" ","").replace("-",""));
                break;
        }
    }

    protected void judgePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 检查该权限是否已经获取
            // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
            //手机状态权限
            String[] SdCdPermission = {Manifest.permission.READ_CONTACTS};
            if (ContextCompat.checkSelfPermission(this, SdCdPermission[0]) != PackageManager.PERMISSION_GRANTED) {
                // 如果没有授予该权限，就去提示用户请求
                ActivityCompat.requestPermissions(this, SdCdPermission, 350);
            }else{
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, 0);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NotNull @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasAllGranted = true;
        //判断是否拒绝  拒绝后要怎么处理 以及取消再次提示的处理
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                hasAllGranted = false;
                break;
            }
        }
        if (hasAllGranted) { //同意权限做的处理,开启服务提交通讯录
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, 0);

        } else {    //拒绝授权做的处理，弹出弹框提示用户授权
            dealwithPermiss(ZeroPointReserveActivity.this, permissions[0]);
        }
    }

    public void dealwithPermiss(final Activity context, String permission) {
        if (!ActivityCompat.shouldShowRequestPermissionRationale(context, permission)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(ZeroPointReserveActivity.this);
            builder.setTitle("操作提示")
                    .setMessage("注意：当前缺少必要权限！\n请点击“设置”-“权限”-打开所需权限\n最后点击两次后退按钮，即可返回")
                    .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", context.getApplicationContext().getPackageName(), null);
                            intent.setData(uri);
                            context.startActivity(intent);
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Toast.makeText(ZeroPointReserveActivity.this, "取消授权", Toast.LENGTH_SHORT).show();
                        }
                    }).show();

        }
    }

}